<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/3/12
 * Time: 上午11:24
 */

namespace Biz\module\Classes;

use Biz\model\ShopSecurityDeposit as mShopSecurityDeposit;
use Biz\model\ShopSecurityDepositLog as mShopSecurityDepositLog;
use Biz\validate\ShopSecurityDeposit as vShopSecurityDeposit;

final class SecurityDeposit
{

    public function operateAmount($uid, $amount, $scenes, $adminUid = 0, $isAbsolute = false)
    {
        if (!vShopSecurityDeposit::validate(['amount' => $amount], $scenes)) {
            $msg = vShopSecurityDeposit::firstError();

            throw new \Exception($msg);
        }

        $operator = '';
        if (!$isAbsolute) {
            $operator = '[+]';
            if ($amount < 0) {
                $operator = '[-]';
            }

        }

        $amount = abs($amount);

        $data = mShopSecurityDeposit::update([
            "amount{$operator}" => $amount,
            'last_amount_adminuid' => $adminUid,
        ], [
            'uid' => $uid,
        ]);
        if ($data->errorCode() !== '00000') {
            throw new \Exception('操作错误，额度不足或账户不存在');
        }

    }

    public function operateBalance($uid, $balance, $type, $transNumber, $transTime, $scenes, $adminUid = 0, $remark = '')
    {
        if (!vShopSecurityDeposit::validate(['amount' => $balance, 'trans_number' => $transNumber], $scenes)) {
            $msg = vShopSecurityDeposit::firstError();

            throw new \Exception($msg);
        }

        if (mShopSecurityDepositLog::hasTransNumber($transNumber)) {
            throw new \Exception('已存在的回单编号');
        }

        $operator = '+';
        if ($balance < 0) {
            $operator = '-';
        }

        $balance = abs($balance);

        $data = mShopSecurityDeposit::update([
            "balance[{$operator}]" => $balance,
            'last_balance_edittime' => date('Y-m-d H:i:s')
        ], [
            'uid' => $uid,
        ]);


        $row = $data->rowCount();

        if ($row == 0) {
            throw new \Exception('操作错误,余额不足或账户不存在');
        }

        //如果操作的是余额则需要追加日志
        $id = mShopSecurityDepositLog::insertLog($uid, [
            'type' => $type,
            'balance' => sprintf('%s%s', $operator, $balance),
            'remark' => $remark,
            'adminuid' => $adminUid,
            'status' => mShopSecurityDepositLog::STATUS_PROCESSED,
            'trans_number' => $transNumber,
            'trans_time' => $transTime,
        ]);

        if (empty($id)) {
            throw new \Exception('写入错误');
        }
        return $id;
    }
}